package com.example.demo.thread.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: liull
 * @Description: Condition类似于Object.wait() notify() notifyAll(), 使用前必须获取锁lock.lock(),await()释放锁直到signal()被调用
 * @Date: Created in 15:19 2020/10/10
 * @Modified By:
 */
public class ConditionTest1 {
    static ReentrantLock lock = new ReentrantLock();

    static Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        lock.lock();
        // 令启一子线程
        new Thread(new SignalThread()).start();
        System.out.println("主线程等待子线程通知");
        try {
            condition.await();
        } finally {
            lock.unlock();
        }
        System.out.println("主线程恢复运行");
    }

    static class SignalThread implements Runnable {

        @Override
        public void run() {
            lock.lock();
            try {
                // 必须获得锁 才可调用signal()方法
                condition.signal();
                System.out.println("子线程通知");
            } finally {
                lock.unlock();
            }
        }
    }

}
